package apis

import (
	"context"
	"gluenet/pkg/log/v1"
	"sync"
	"time"
)

type Gflush struct {
	Info  *sync.Map
	Func  *sync.Map
	ctx   context.Context
	time  time.Duration
	close context.Context
}

func NewGflush(ctx context.Context, time time.Duration) *Gflush {
	return &Gflush{
		ctx:  ctx,
		time: time,
		Info: &sync.Map{},
		Func: &sync.Map{},
	}
}

func (r *Gflush) Run(logger v1.Logger) {
	tk := time.NewTicker(r.time)
	//ctx, cancel := context.WithCancel(context.Background())
	//r.close = ctx
	go func() {
		for true {
			select {
			case <-r.ctx.Done():
				//cancel()
				return
			case <-tk.C:
				//logger.Debugf("flush")
				r.Info.Range(func(key, value interface{}) bool {
					fi, _ := r.Func.Load(key)
					f := fi.(func(key, value interface{}) error)
					if err := f(key, value); err != nil {
						logger.Errorf("flush info failed")
					}
					return true
				})
			}
		}
	}()
}

func (r *Gflush) Close() error {
	r.Info.Range(func(key, value interface{}) bool {
		fi, _ := r.Func.Load(key)
		f := fi.(func(key, value interface{}) error)
		f(key, value)
		return true
	})
	//<-r.close.Done()
	return nil
}
